package com.zlll.winner.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.integration.redis.util.RedisLockRegistry;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;

/**
 * @program: oss
 * @description: redis分布式锁-Spring Integration
 * @author: zdh
 * @date: 2019-07-29 18:14
 **/
@Service
@Slf4j
public class RedisLockWithIntegration {

    private static int tryCount = 5;
    private static int waitSecond = 1;

    @Autowired
    private RedisLockRegistry redisLockRegistry;

    public Lock getLock(String key, int second, boolean wait) {
        Lock lock = redisLockRegistry.obtain(key);
        boolean b1;
        try {
            b1 = lock.tryLock(second, TimeUnit.SECONDS);
            if (b1) {
                // 获得锁
                return lock;
            }else {
                // 没得锁
                if (wait) {
                    //重试
                    for (int i = 0; i < tryCount; i++) {
                        //等待1秒
                        TimeUnit.SECONDS.sleep(second);
                        //尝试获取锁
                        b1 = lock.tryLock(waitSecond, TimeUnit.SECONDS);
                        if (b1) {
                            //获取到锁立即返回
                            return lock;
                        }
                    }
                }
                return null;
            }
        } catch (Exception e) {
            log.error("redis分布式锁出错，{}",e);
            if (lock != null) {
                lock.unlock();
            }
            return null;
        }
    }
}
